﻿using Microsoft.AspNetCore.Authentication.OAuth;
using System.Text.Json;
using static OAuthClient.Server.TokenManage;

namespace OAuthClient.Server
{
    public class Refresh
    {
        private readonly HttpClient _httpClient;

        public Refresh(IHttpClientFactory clientFactory)
        {
            _httpClient = clientFactory.CreateClient();
        }

        public async Task<OAuthTokenResponse> RefreshToken(TokenInfo info)
        {
            var tokenPara = new Dictionary<string, string>()
        {
            {"client_id","liya00" },
            {"client_secret","123" },
            {"grant_type","refresh_token" },
            {"refresh_token", info.RefreshToken}
        };

            var requestContent = new FormUrlEncodedContent(tokenPara);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://localhost:5005/oauth/RefreshToken");

            requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            requestMessage.Content = requestContent;
            requestMessage.Version = _httpClient.DefaultRequestVersion;
            var response = await _httpClient.SendAsync(requestMessage);
            var body = await response.Content.ReadAsStringAsync();

            return OAuthTokenResponse.Success(JsonDocument.Parse(body));
        }


    }
}
